home *** CD-ROM | disk | FTP | other *** search
Wrap
//Helper functions and objects var AppInfo = { //consts WIN: "WIN", MAC: "MAC", LINUX: "LINUX", //public properties OS: "", browserVersion: "", isGecko191: null, //FF3.5 and up isGecko19: null, //FF3 and up isGecko18: null, //FF2 and up xulRuntime: null, compareVersions: function(strVer1, strVer2) { var oVersionCompare = Components.classes["@mozilla.org/xpcom/version-comparator;1"] .createInstance(Components.interfaces.nsIVersionComparator); return oVersionCompare.compare(strVer1, strVer2); }, getOS: function() { try { var window = getWindow(); var strUserAgent = window.navigator.userAgent; var iStart = strUserAgent.indexOf('('); var iEnd = strUserAgent.indexOf(')'); var strPlatformData = strUserAgent.substring(iStart, iEnd); var arrData = strPlatformData.split(';'); return arrData[2].replace(/\s/g, ""); } catch (e) { return ""; } }, isVista: function() { var os = this.getOS().toUpperCase(); if (os.indexOf(this.WIN) == -1) return false; os = os.replace(/\./g, ""); var ver = os.match(/(\d+)/); return parseInt(ver) >= 60 }, init: function() { //parse OS type try { this.xulRuntime = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULRuntime); var _os = this.xulRuntime.OS.toUpperCase(); if (_os.indexOf(this.WIN) != -1) { this.OS = this.WIN; } else if (_os.indexOf(this.MAC) != -1) this.OS = this.MAC; else this.OS = this.LINUX; //set gecko version (1.8.x or 1.9.x) var _geckoVer = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULAppInfo).platformVersion; this.browserVersion = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULAppInfo).version; var strGeckoVer = "1.9.0.0"; //FF3 gecko version var iCompare = this.compareVersions(_geckoVer, strGeckoVer); this.isGecko19 = (iCompare >= 0); strGeckoVer = "1.9.1.0"; //FF3.5 gecko version var iCompare = this.compareVersions(_geckoVer, strGeckoVer); this.isGecko191 = (iCompare >= 0); strGeckoVer = "1.8.0.0"; //FF2 gecko version iCompare = this.compareVersions(_geckoVer, strGeckoVer); this.isGecko18 = (iCompare >= 0); } catch (e) { Logging.LogToConsole(e) } } }; AppInfo.init(); var EBServerDataURL = { ServerRequest : function(strURL,strPostData,strUserName,strPassword,ServerResponseFunction) { var objIOService = Components.classes["@mozilla.org/network/io-service;1"].createInstance(Components.interfaces.nsIIOService); var objURI = objIOService.newURI(strURL, null, null); if(strUserName != null && strPassword != null) { objURI.username = strUserName; objURI.password = strPassword; } var objChannel = objIOService.newChannelFromURI(objURI); objChannel.QueryInterface(Components.interfaces.nsIHttpChannel).setRequestHeader('PRAGMA','NO-CACHE',false); objChannel.QueryInterface(Components.interfaces.nsIHttpChannel).setRequestHeader('CACHE-CONTROL','NO-CACHE',false); if(strPostData != null) { var objUploadStream = Components.classes["@mozilla.org/io/string-input-stream;1"].createInstance(Components.interfaces.nsIStringInputStream); objUploadStream.setData(strPostData, strPostData.length); var objUploadChannel = objChannel.QueryInterface(Components.interfaces.nsIUploadChannel); objUploadChannel.setUploadStream(objUploadStream, "application/x-www-form-urlencoded", -1); objChannel.QueryInterface(Components.interfaces.nsIHttpChannel).requestMethod = "POST"; } var objObserver = new this.Observer(ServerResponseFunction); objChannel.asyncOpen(objObserver, null); }, Observer: function(ServerResponseFunction) { return ({ Data : "", onStartRequest: function(aRequest, aContext) { this.Data = ""; }, onStopRequest: function(aRequest, aContext, aStatus) { if(ServerResponseFunction) { ServerResponseFunction(this.Data, aRequest); } }, onDataAvailable: function(aRequest, aContext, aStream, aSourceOffset, aLength) { var objScriptableInputStream = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream); objScriptableInputStream.init(aStream); this.Data += objScriptableInputStream.read(aLength); } }); } }; if (typeof JSON == "undefined") { //FF3.5 if (AppInfo.isGecko191) { //do nothing } //FF3 else if (AppInfo.isGecko19) { var myJson = Components.classes["@mozilla.org/dom/json;1"].createInstance(Components.interfaces.nsIJSON); JSON = {}; JSON.stringify = function(obj) { return myJson.encode(obj); }; JSON.parse = function(str) { return myJson.decode(str); }; } //FF2 else { var myJson = { stringify: function(aJSObject, aKeysToDrop) { var pieces = []; function append_piece(aObj) { if (typeof aObj == "string") { aObj = aObj.replace(/[\\"\x00-\x1F\u0080-\uFFFF]/g, function($0) { switch ($0) { case "\b": return "\\b"; case "\t": return "\\t"; case "\n": return "\\n"; case "\f": return "\\f"; case "\r": return "\\r"; case '"': return '\\"'; case "\\": return "\\\\"; } return "\\u" + ("0000" + $0.charCodeAt(0).toString(16)).slice(-4); }); pieces.push('"' + aObj + '"') } else if (typeof aObj == "boolean") { pieces.push(aObj ? "true" : "false"); } else if (typeof aObj == "number" && isFinite(aObj)) { pieces.push(aObj.toString()); } else if (aObj === null) { pieces.push("null"); } else if (aObj instanceof Array || typeof aObj == "object" && "length" in aObj && (aObj.length === 0 || aObj[aObj.length - 1] !== undefined)) { pieces.push("["); for (var i = 0; i < aObj.length; i++) { arguments.callee(aObj[i]); pieces.push(","); } if (aObj.length > 0) pieces.pop(); // drop the trailing colon pieces.push("]"); } else if (typeof aObj == "object") { pieces.push("{"); for (var key in aObj) { // allow callers to pass objects containing private data which // they don't want the JSON string to contain (so they don't // have to manually pre-process the object) if (aKeysToDrop && aKeysToDrop.indexOf(key) != -1) continue; arguments.callee(key.toString()); pieces.push(":"); arguments.callee(aObj[key]); pieces.push(","); } if (pieces[pieces.length - 1] == ",") pieces.pop(); // drop the trailing colon pieces.push("}"); } else { throw new TypeError("No JSON representation for this object!"); } } append_piece(aJSObject); return pieces.join(""); }, /** * Converts a JSON string into a JavaScript object. * * @param aJSONString is the string to be converted * @return a JavaScript object for the given JSON representation */ parse: function(aJSONString) { if (!this.isMostlyHarmless(aJSONString)) throw new SyntaxError("No valid JSON string!"); var s = new Components.utils.Sandbox("about:blank"); return Components.utils.evalInSandbox("(" + aJSONString + ")", s); }, /** * Checks whether the given string contains potentially harmful * content which might be executed during its evaluation * (no parser, thus not 100% safe! Best to use a Sandbox for evaluation) * * @param aString is the string to be tested * @return a boolean */ isMostlyHarmless: function(aString) { var maybeHarmful = /[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/; var jsonStrings = /"(\\.|[^"\\\n\r])*"/g; return !maybeHarmful.test(aString.replace(jsonStrings, "")); } } JSON = myJson; } }; function decodeUtf8(utftext) { var string = ""; var i = 0; var c = c1 = c2 = 0; while ( i < utftext.length ) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i+1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; } function setTimeout(objDeligate, iTimeout) { var timer = Components.classes['@mozilla.org/timer;1']. createInstance(Components.interfaces.nsITimer); timer.initWithCallback(objDeligate, iTimeout, Components.interfaces.nsITimer.TYPE_ONE_SHOT); } //XPCOM function ConduitAutoCompleteSearch() { this.commands = []; this.txtSuggest = "Suggestions"; this.txtHistory = "History"; this.wrappedJSObject = this; }; ConduitAutoCompleteSearch.prototype = { lastSuggetTimestamp : '', searchString : '', setCaptions: function(txtSuggest, txtHistory) { this.txtSuggest = txtSuggest; this.txtHistory = txtHistory; }, startSearch: function(searchString, strJsonData, prevResult, listener) { this.requestSuggestions(searchString, listener, strJsonData); }, stopSearch: function() {}, requestSuggestions : function(searchString, listener, strJSON) { var objData = JSON.parse(strJSON); var strSuggestUrl = objData.suggestUrl; this.setCaptions(objData.txtSuggest, objData.txtHistory); //no suggestions for this engine this.searchString = searchString; if(!strSuggestUrl || !searchString) { //load local history only this.setSuggestionsAndHistory(searchString, null, listener); return; } //go get suggestions var now = Date.parse(Date()); var arrSuggestUrl = strSuggestUrl.split('!!'); strSuggestUrl = arrSuggestUrl[0]; var strSearchTermToReplace = arrSuggestUrl[1]; strSuggestUrl = strSuggestUrl.replace(strSearchTermToReplace,escape(searchString)); var objFunc = this; var oResponse = function(strJSON) { objFunc.setSuggestionsAndHistory(searchString,strJSON,listener); }; var oRequest = { originalSearchString : searchString, notify : function(oTimer) { if(this.originalSearchString == objFunc.searchString) this.execute(); }, execute : function() { EBServerDataURL.ServerRequest(strSuggestUrl,null,null,null,oResponse); }, }; setTimeout(oRequest,300); }, setSuggestionsAndHistory: function(searchString, strJSON, listener) { var dir = null; var bLoadHistory = true; try { var dir = Components.classes['@mozilla.org/file/directory_service;1'] .createInstance(Components.interfaces.nsIProperties) .get('ProfD', Components.interfaces.nsIFile); var sep = '/'; var path = dir.path + sep + 'EBSuggestHistory'; try { var ebDir = Components.classes['@mozilla.org/file/local;1'] .createInstance(Components.interfaces.nsILocalFile); ebDir.initWithPath(path); } catch(e) { sep = '\\'; path = dir.path + sep + 'EBSuggestHistory'; try { var ebDir = Components.classes['@mozilla.org/file/local;1'] .createInstance(Components.interfaces.nsILocalFile); ebDir.initWithPath(path); } catch(e) {} } var file = Components.classes['@mozilla.org/file/local;1'] .createInstance(Components.interfaces.nsILocalFile); file.initWithPath(ebDir.path + sep + 'search_history.xml'); var data = new String(); var fiStream = Components.classes['@mozilla.org/network/file-input-stream;1'] .createInstance(Components.interfaces.nsIFileInputStream); var siStream = Components.classes['@mozilla.org/scriptableinputstream;1'] .createInstance(Components.interfaces.nsIScriptableInputStream); fiStream.init(file, 1, 0, false); siStream.init(fiStream); data += siStream.read(-1); siStream.close(); fiStream.close(); var uniConv = Components.classes['@mozilla.org/intl/scriptableunicodeconverter'] .createInstance(Components.interfaces.nsIScriptableUnicodeConverter); uniConv.charset = 'UTF-8'; data = uniConv.ConvertToUnicode(data); } catch(e) { bLoadHistory = false; } if(bLoadHistory) { var parser = Components.classes['@mozilla.org/xmlextras/domparser;1'] .createInstance(Components.interfaces.nsIDOMParser); var xmlDoc = parser.parseFromString(data, "text/xml"); var xmlItems = xmlDoc.documentElement.getElementsByTagName('ITEM'); var result = []; var nodeValue = ''; for(var i=0; i<xmlItems.length; i++) { if(typeof (xmlItems.item(i).childNodes[0]) != "undefined") { nodeValue = xmlItems.item(i).childNodes[0].nodeValue; result[result.length] = nodeValue; } } var commands = Components.classes["@mozilla.org/supports-array;1"].createInstance(Components.interfaces.nsISupportsArray); for (var i = 0; i < result.length; i++) { var string = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString); string.data = result[i]; commands.AppendElement(string); } var count = commands.Count(); this.commands = new Array(count); for (var i = 0; i < count; i++) this.commands[i] = commands.GetElementAt(i).QueryInterface(Components.interfaces.nsISupportsString).data; } var arrSuggest = null; if (strJSON && strJSON.length > 0) arrSuggest = JSON.parse(strJSON); var result = new AutoCompleteResult(searchString, this.commands, arrSuggest, this.txtSuggest, this.txtHistory); listener.onSearchResult(this, result); }, QueryInterface: function (uuid) { if (uuid.equals(Components.interfaces.nsIConduitAutoCompleteSearch) || uuid.equals(Components.interfaces.nsIAutoCompleteSearch) || uuid.equals(Components.interfaces.nsISupports)) { return this; } Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE; return null; } } function AutoCompleteResult(search, commands, arrSuggest, txtSuggest, txtHistory) { var IsContains = function(arrArray, strString) { for(var i=0; i<arrArray.length; i++) if(arrArray[i] == strString) return true; return false; }; this.search = search; this.commands = []; this.txtSuggest = txtSuggest; this.txtHistory = txtHistory; var lsearch = search.toLowerCase(); if(commands.length > 0) { for (var i = 0; i < commands.length; i++) { if (commands[i].toLowerCase().indexOf(lsearch) == 0) this.commands.push(commands[i]); } } this.HistoryStartIndex = this.commands.length; if(arrSuggest && search == decodeUtf8(arrSuggest[0]) && arrSuggest[1].length > 0) { for(var i=0; i<arrSuggest[1].length; i++) { if(!IsContains(this.commands ,arrSuggest[1][i])) this.commands.push(decodeUtf8(arrSuggest[1][i])); } } } AutoCompleteResult.prototype = { get defaultIndex() { return 0; }, get errorDescription() { return ''; }, get matchCount() { return this.commands.length; }, get searchResult() { return Components.interfaces.nsIAutoCompleteResult.RESULT_SUCCESS; }, get searchString() { return this.search; }, getCommentAt: function(index) { if(index == this.HistoryStartIndex) return this.txtSuggest; else if(index == 0) return this.txtHistory; else return ''; }, getStyleAt: function(index) { if (!this.commands[index]) return null; // not a category label, so no special styling if (index == 0) return "suggestfirst"; // category label on first line of results if(index == this.HistoryStartIndex) return "suggesthint"; return ''; }, getValueAt: function(index) { return this.commands[index]; }, removeValueAt: function(rowIndex, removeFromDb) { }, getImageAt: function(index) { return ""; }, QueryInterface: function (uuid) { if (uuid.equals(Components.interfaces.nsIAutoCompleteResult) || uuid.equals(Components.interfaces.nsISupports)) { return this; } Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE; return null; } }; const COMPONENT_ID = Components.ID("{FDE25E06-0242-4b4f-A202-5B0DA44243B9}"); var ConduitAutoCompleteModule = { registerSelf: function (compMgr, fileSpec, location, type) { compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar); compMgr.registerFactoryLocation(COMPONENT_ID, "Conduit Auto Complete with Suggest", "@mozilla.org/autocomplete/search;1?name=conduit-auto-complete-with-suggest3", fileSpec, location, type); }, getClassObject: function (compMgr, cid, iid) { if (!cid.equals(COMPONENT_ID)) throw Components.results.NS_ERROR_NO_INTERFACE; if (!iid.equals(Components.interfaces.nsIFactory)) throw Components.results.NS_ERROR_NOT_IMPLEMENTED; return ConduitAutoCompleteFactory; }, canUnload: function(compMgr) { return true; } }; var ConduitAutoCompleteFactory = { createInstance: function (outer, iid) { if (outer != null) throw Components.results.NS_ERROR_NO_AGGREGATION; return new ConduitAutoCompleteSearch().QueryInterface(iid); } }; function NSGetModule(compMgr, fileSpec) { return ConduitAutoCompleteModule; };